# coding="utf-8"
# https://blog.csdn.net/feiyang5260/article/details/82150845
import requests
from time import sleep
from prettytable import PrettyTable


# 从东方财富网获取
def getQuotes1(url):
    # 主要是获取user-agent，伪装成浏览器，其它的可要，可不要
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
    }
    web_data = requests.get(url,
                            headers=header)  # Request有三个参数（url,data,headers）,如果有使用data就是post请求了，没有就是get请求。这里我没有data，所以我就指定headers=header，不然header就会被当成data了。
    web_data.encoding = "utf-8"
    data = web_data.text
    # print(data)
    # 以下操作是要是对获取到的数据做一些处理(截取所需字符串，变为列表后输出易于观察)
    # 截取字符串中[]以内的数据
    pos_start = data.find("[")
    pos_end = data.find("]")
    # print(pos_start, pos_end)
    data = data[pos_start + 1:pos_end]
    # 字符串以","这三个字符隔开，且以列表保存
    data = data.split('\",\"')
    # 除掉列表中首尾位置字符串中的双引号
    data[0] = data[0].replace("\"", "")
    data[-1] = data[-1].replace("\"", "")
    pt = PrettyTable()
    pt._set_field_names(('指数简称 指数名称 最新价 涨跌额 涨跌幅 开盘 最高 最低 昨收 振幅 更新时间').split())
    for one in data:
        # print(one)
        # print(type)
        onelist = one.split(
            ',')  # 如['_UI', 'FTSE', '英国富时100', '7487.25', '54.83', '0.74%', '2018-09-03 16:16:46', '0', '7451.50', '7487.25', '7451.50', '7432.42', '0.48']
        # print(one.split(','))
        english = onelist[1]  # 简称英文
        name = onelist[2]  # 简称中文
        price = onelist[3]  # 最新价
        change = onelist[4]  # 涨跌额
        zhangdiefu = onelist[5]  # 涨跌幅
        updatetime = onelist[6]  # 更新时间
        open = onelist[8]  # 开盘价
        high = onelist[9]  # 最高价
        low = onelist[10]  # 最低价
        zuoshou = onelist[11]  # 昨收
        amplitude = onelist[12]  # 振幅
        pt.add_row([english, name, price, change, zhangdiefu, open, high, low, zuoshou, amplitude, updatetime])
    # 显示行情数据
    print('以下数据来自东方财富网')
    print(pt)


if __name__ == "__main__":
    # 美洲市场
    url_ame = "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery1124041818616891656046_1535426942953&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FCRH&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C._UI_MAP_AME&st=(Tag)&sr=1&p=1&ps=20&_=1535426942954"
    getQuotes1(url_ame)
